import AniBox from '../libs/AniBox.esm.js'
import { convertPosition } from './main.js'
import store from '../store/index.js'
import { zrender } from '../libs/zrender-helper.js'

export function createEne(){
  let { main } = store.state;
  let config = store.state.config.enemy;
  let ene = new AniBox({
    data(){
      return {
        x : Math.random() * (config.r - config.l) + config.l,
        //x : 0,
        y : config.y,
        level : 1, //等级
        stock : 3, //血量
        w : config.w,
        h : config.h,
        status : 1, //1活跃 2摧毁
      }
    },
    methods : {
      move(){
        this.y -= config.vy;
      },
      inShoot(shoot){
        let { power } = shoot;
        let stock = this.stock;
        stock -= power;
        if(stock <= 0){
          this.destroy();
        }
        this.stock = stock;
      },
      checkShoot(){
        let { shoots } = store.state.player;
        shoots.forEach(shoot => {
          if(shoot.x >= this.x && shoot.x <= this.x + this.w){
            if(shoot.y <= this.y && shoot.y >= this.y - this.h){
              this.inShoot(shoot);
              shoot.destroy();
            }
          }
        });
      },
      //超出范围销毁
      checkOutRange(){
        if(this.y <= 0){
          this.destroy();
        }
      },
      destroy(){
        this.sleep();
        this.status = 2;
        main.remove(this.shape);
        this.context.remove(this);
      }
    },
    created(){
      this.shape = new zrender.Rect({
        shape : {
          width : this.w,
          height : this.h
        }
      });
      main.add(this.shape);
    },
    step(){
      this.checkShoot();
      this.checkOutRange();
      this.move();
    },
    render(){
      this.shape.attr({
        position : convertPosition([this.x,this.y])
      })
    }
  });
  return ene;
}
